<?php

namespace Tian\Controller;

use QueryList;
use PclZip;

class WebsiteController extends CommonController {

    public function lists() {//参考网站
        $count = M('website')->count();    //计算总数
        $Page = new \Think\Page($count, C("pagenum"));
        $lists = M('website')->limit($Page->firstRow . ',' . $Page->listRows)->order('is_complete ASC,id DESC')->select();
        $this->assign("page", $Page->show());
        $this->assign("lists", $lists);
        $this->display();
    }

    public function detail() {//参考网站详情
        $id = I("get.id", 0, 'int');
        if ($id > 0) {
            $detail = M('website')->where("id = " . $id . "")->find();
            $jsons = json_decode($detail['json'], true);
            $jsons2 = json_decode($detail['json2'], true);
            $nodates = explode(",", $detail['nodata']);
        } else {
            $detail['is_check'] = 1;
            $jsons = array(0 => array("urls" => '', "codes" => ''));
        }
//        $file_path_root =  "ba/";
//        $file_path = "../".$file_path_root;
//            $filesScandir = scandir($file_path);
//           
//            foreach ($filesScandir as $k => $v) {
//                $type = get_extension($v);
//                if ($type == 'html') {
//                    $jsons[$k]['urls'] = "http://localhost/".$file_path_root."".$v;
//                    $jsons[$k]['codes'] = str_replace(".html", "", $v);
//                    $content = htmlspecialchars_decode(file_get_contents($file_path . $v));
//                    file_put_contents($file_path.$v, $content);
//                    preg_match_all('/<title>(.*)<\/title>/', $content, $titleMacth);
//                    $jsons[$k]['names'] = $titleMacth[1][0];
//                
//                }
//            }
////             print_r($jsons);
        $this->assign("detail", $detail);
        $this->assign("jsons", $jsons);
        $this->assign("jsons2", $jsons2);
        $this->assign("nodates", $nodates);
        $this->display();
    }

    public function detail_post() {
        $id = I("post.id", 0, 'int');
        $data['state'] = I("post.state", 0, 'int');
        $data['reason'] = trim(I("post.reason"));
        $data['name'] = trim(I("post.name"));
        $data['ord'] = I("post.ord", 0, 'int');
        $data['modal_id'] = I("post.modal_id", 0, 'int');
        $data['website'] = trim(I("post.website"));
        $data['website2'] = trim(I("post.website2"));
        $parse_url = parse_url($data['website']);
        $websiteArr = explode(".", $parse_url["host"]);
        $website_name = $websiteArr[1];
        if (in_array($website_name, array("com", "cn", "net"))) {
            $data['name_short'] = $websiteArr[0];
        } else {
            $data['name_short'] = $website_name;
        }

        $urls = array_unique(array_filter(I('post.urls')));
        $codes = array_unique(array_filter(I('post.codes')));
        $names = array_unique(array_filter(I('post.names')));
        $website_chose = array_filter(I('post.website_chose'));
        $urls_real = array_unique(array_filter(I('post.urls_real')));
        $json = array();
        if ($urls) {
            foreach ($urls as $k => $v) {
                if ($v) {
                    $json[$k]['urls'] = $v;
                    $json[$k]['codes'] = $codes[$k];
                    $json[$k]['names'] = $names[$k];
                    $json[$k]['website_chose'] = $website_chose[$k];
                    $json[$k]['urls_real'] = $urls_real[$k];
                }
            }
            $data['json'] = json_encode($json);
        } else {
            $data['json'] = "";
        }

        $urls2 = array_unique(array_filter(I('post.urls2')));
        $codes2 = array_unique(array_filter(I('post.codes2')));
        $names2 = array_unique(array_filter(I('post.names2')));
        $json2 = array();
        if ($urls2) {
            foreach ($urls2 as $k => $v) {
                if ($v) {
                    $json2[$k]['urls2'] = $v;
                    $json2[$k]['codes2'] = $codes2[$k];
                    $json2[$k]['names2'] = $names2[$k];
                }
            }
            $data['json2'] = json_encode($json2);
        } else {
            $data['json2'] = "";
        }
        if ($data['modal_id'] > 0) {
            $info = M('website')->where("id = " . $id . "")->find();
            if ($info['uid'] > 0) {
                M('modals')->where("id = " . $data['modal_id'] . "")->save(array("uid" => $info['uid']));
            }
        }
        if ($id > 0) {
            M('website')->where("id = " . $id . "")->save($data);
            $this->redirect("Website/detail", array("id" => $id));
        } else {
            $data['addtime'] = time();
            M('website')->add($data);
            $this->success("添加参考网站成功！", U("Website/lists"));
        }
    }

    public function modal_unzip_images() {
set_time_limit(0);
        $pattern_img = "/<img.*?src=[\\\'| \\\"](.*?(?:[\.gif|\.jpg]))[\\\'|\\\"].*?[\/]?>/";
      
        include_once 'common/website_get_files.php';
        $url_post = I("post.url_post");
        $content = file_get_contents($url_post);

        preg_match_all($pattern_img, $content, $imagesMatch1);
        $imagesArr1 = $imagesMatch1[1];
        $regex = '/url\(\'{0,1}\"{0,1}(.*?)\'{0,1}\"{0,1}\)/';
        preg_match_all($regex, $content, $imagesMatch2);
        $imagesArr2 = $imagesMatch2[1];
        if ($imagesArr1 && $imagesArr2) {
            $merge = array_merge($imagesArr1, $imagesArr2);
        } else {
            $merge = $imagesArr1 ? $imagesArr1 : $imagesArr2;
        }
        if ($merge) {
            $websiteModal = new \Tian\Model\WebsiteModel();
            foreach ($merge as $v) {
                $img = getCurlImg($v, $website);
                $websiteModal->getImages($img, $website_name);
            }
        }
    }

    public function modal_unzip_js() {
         // exit;
        set_time_limit(0);
        include_once 'common/website_get_files.php';
        $websiteModal = new \Tian\Model\WebsiteModel();
        $url_post = I("post.url_post");
        $content = file_get_contents($url_post);
        $pattern = '/<script.+?src=(\'|")(.+?)\\1/s';
        preg_match_all($pattern, $content, $jsMatch);
        $jsArr = $jsMatch[2];
        foreach ($jsArr as $v) {
            if ($v) {
                $jsExplode = explode(",", $v);
                
                if (count($jsExplode) == 1) {
                    $url_per = getCurlPerFile($v, $website, $info['website']);
                    foreach ($url_per as $v2) {
                        $websiteModal->getJs($v2, $dir_website);
                    }
                } else {
                    $url_js_first = $jsExplode[0];
                    $url_js_first_arr = explode("=",$jsExplode[0]);
                    $url_js_front = $url_js_first_arr[0]."=";
                    foreach ($jsExplode as $k5=>$v5) {
                        if($k5 ==0){
                            $url_js = $v5;
                        }else{
                                  $url_js = $url_js_front.trim($v5);
                        }
                        $url_per = getCurlPerFile($url_js, $website, $info['website']);
                        foreach ($url_per as $v2) {
                            $websiteModal->getJs($v2, $dir_website);
                        }
                    }
                }
            }
        }
    }

    public function modal_unzip_css_images() {//获取css包括images
        set_time_limit(0);
        include_once 'common/website_get_files.php';
        $websiteModal = new \Tian\Model\WebsiteModel();
        $url_post = I("post.url_post");

        $new = file_get_contents($url_post);
        preg_match_all('/<link.+?href=(\'|")(.+?)\\1/s', $new, $cssMatch);
        $cssArr = $cssMatch[2];
        $nodata = $info['nodata'];

        if ($nodata) {
            $nodatas = explode(",", $nodata);
        } else {
            $nodatas = array();
        }

        foreach ($cssArr as $v) {
            if ($v) {
                $url_per_arr = getCurlPerFile($v, $website, $info['website']);
                foreach ($url_per_arr as $v2) {
                   
                    $websiteModal->getCssImages($v2, $dir_website, $website); //css中images 归类
                }
            }
        }
        if ($nodatas) {
            $data['nodata'] = implode(",", $nodatas);
            M("website")->where("id = " . $id . "")->save($data);
        }
    }

    public function modal_unzip_html() {//获取html
        header("Content-type: text/html; charset=utf-8");
        set_time_limit(0);
        include_once 'common/website_get_files.php';

        $websiteModal = new \Tian\Model\WebsiteModel();

        $id = I("post.id");
        $url_post = I("post.url_post");

        $name_post = I("post.name_post");
        $code_post = I("post.code_post");
        $content = file_get_contents($url_post);
        $charset = getCharset($content);
        $new = $content;

        $new = $websiteModal->getReplaceHref($new, $id, $url_post); //替换链接
        //采集图片img src input type=image
        $pattern = array("images" => array("img", "src"), "images2" => array("input", "src"));
        $qy = new QueryList($url_post, $pattern, '', '', 'utf-8');
        $rs = $qy->jsonArr;

        $img_num = count($rs);
        foreach ($rs as $k => $v) {
            if ($v['images2']) {
                $rs[$k + $img_num]['images'] = $v['images2'];
            }
        }

        /*         * ****匹配html background url**** */
        $preg_background_url = "/url\((.*)\)/"; ///background[^;]+;/
        preg_match_all($preg_background_url, $new, $background_urls);
        $background_urls_img = $background_urls[1];
        $num = count($rs);
        foreach ($background_urls_img as $k => $v) {
            $rs[$k + $num]['images'] = $v;
        }

        foreach ($rs as $v) {
            $name = basename($v['images']);
            $name_shortest = get_extension_basename($name);
            if (is_img_basename($name_shortest) >= 1) {
                $img = getCurlImg($v['images'], $website);
                $rs = $websiteModal->getImages($img, $website_name);
                $new = str_replace($v['images'], 'images/' . $name, $new);
            } else {
            }
        }
        $new = $websiteModal->getHtmlCss($new, $website_name); //替换css

        $new = $websiteModal->getHtmlJs($new, $website_name); //替换js
        $new = $websiteModal->getHtmlTitle($new, $name_post, $code_post); //替换网页标题
        $new = $websiteModal->getHtmlHref($new, $id); //替换链接
        $new = $websiteModal->getHtmlStatics($new); //替换统计代码
        $new = $websiteModal->getHtmlEmpty($new); //关键词为空 放在最后
        $new = $websiteModal->getHtmlExchange($new, $id, $charset); //关键词替换 放在最后
        $new = $websiteModal->getLastImages($new, $website, $website_name); //图片扫尾
        if (strtolower($charset) != 'utf-8' && $charset != '') {
            $new = iconv($charset, "utf-8", $new);
        }
        file_put_contents($dir_website . "/" . $code_post . ".html", $new);
    }

    public function html_format() {

        header("Content-type: text/html; charset=utf-8");
        include_once 'common/website_get_files.php';
        $websiteModal = new \Tian\Model\WebsiteModel();
        $filesScandir = scandir($dir_website);


        foreach ($filesScandir as $v) {
            $type = get_extension($v);

            if ($type == 'html') {
                $page_html = $dir_website . "/" . $v;
                if (file_exists($page_html)) {
                    $content = $websiteModal->htmlFormatCurl($page_html);

                    file_put_contents($page_html, $content);
                }
            }
        }
    }

    public function html_zip() {
        header("Content-type: text/html; charset=utf-8");
        include_once 'common/website_get_files.php';
        import("Common.Org.PclZip");
        $zip = new PclZip("website/" . $website_name . ".zip");
        $v_list = $zip->create($dir_website, PCLZIP_OPT_REMOVE_PATH, 'website');
    }

    public function modal_link_css_images() {//更换链接
        set_time_limit(0);
        include_once 'common/website_get_files.php';
        $websiteModal = new \Tian\Model\WebsiteModel();
        $detail = M('website')->where("id = " . $id . "")->find();
        $nodatesArr = explode(",", $detail['nodata']);

        $website = I("post.website");

        $nodatas = array();
        foreach ($nodatesArr as $v) {
            if ($v) {
                $url_per = getCurlPerFile($v, $website);
                $url_per = $url_per[0];
                if (!file_exists($url_per)) {
                    if (!in_array($url_per, $nodatas)) {
                        array_push($nodatas, $v);
                    }
                } else {

                    $websiteModal->getCssImages($url_per, $dir_website); //css中images 归类
                }
            }
        }
        if ($nodatas) {
            $data['nodata'] = implode(",", $nodatas);
            M("website")->where("id = " . $id . "")->save($data);
        }
    }

}
